package auctionhaus

class Bid {
    Customer bidder
    Listing listing
    Double amount
    Date dateCreated
    static belongsTo = [Customer, Listing]

    static constraints = {
        amount(nullable:false, validator: {val, obj->
            if (obj.id == null) {
                def max = obj.listing.startingBidAmount
                if (obj.listing.bids.size() == 0 && val < max + 0.5) {
                     return 'firstbidtoosmall'
                }
                obj.listing.bids.each { bid ->
                    if (bid.amount > max && !bid.is(obj)) {
                        max = bid.amount
                    }
                }
                if (val < max + 0.5) {
                    return 'increasetoosmall'
                }
            }
            return true
        })

    }

    static namedQueries = {
        forListing { paramListing ->
            listing {
                eq 'id', paramListing.id
            }

        }
    }
}
